package com.leyou.item.web;

import com.leyou.common.annotation.EnableExceptionAnnotation;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.service.CategoryService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;


/**
 * 分类管理
 */
@RestController
@RequestMapping("category")
@EnableExceptionAnnotation
public class CategoryController {

    private final CategoryService categoryService;

    public CategoryController(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    /**
     *
     * 根据分类ID查询
     * @param id
     * @return CategoryDTO
     */

    @GetMapping("/{id}")
    public ResponseEntity<CategoryDTO> queryCategoryById(@PathVariable("id") long id){

        //返回CategoryDTO
        return  ResponseEntity.ok(new CategoryDTO(categoryService.getById(id)));
    }

    /**
     * 根据ids查询
     * @param ids
     * @return List<CategoryDTO>
     */

    @GetMapping("/list")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByIds(@RequestParam("ids") List<Long> ids){
        //根据ids查询
        List<Category> categoryList = categoryService.listByIds(ids);
        //工具类转换集合的泛型Category ->CategoryDTO
        List<CategoryDTO> categoryDTOList = CategoryDTO.convertEntityList(categoryList);
        /*  ArrayList<CategoryDTO> categoryDTOList = new ArrayList<>(categoryList.size());

        for (Category category : categoryList) {
            categoryDTOList.add(new CategoryDTO(category));
        }*/

        //stream流
        // List<CategoryDTO> categoryDTOList = categoryList.stream().map(category -> new CategoryDTO(category)).collect(Collectors.toList());
        // List<CategoryDTO> categoryDTOList = categoryList.stream().map(CategoryDTO:: new).collect(Collectors.toList());

        return ResponseEntity.ok(categoryDTOList);
    }

    /**
     * 根据brandId查询
     * @param brandId
     * @return List<CategoryDTO>
     */

    @GetMapping("/of/brand")
    public ResponseEntity<List<CategoryDTO>>  queryCategoryByBrandId( @RequestParam("id") long brandId){

       List<CategoryDTO> list =  categoryService.queryByBid(brandId);

       return ResponseEntity.ok(list);
    }

    /**
     * 根据pid批量查询
     * @param pid
     * @return List<CategoryDTO>
     */
    @GetMapping("/of/parent")
    public ResponseEntity<List<CategoryDTO>> queryByParentId(@RequestParam("pid") long pid){
        //根据pid批量查询
        List<Category> list = categoryService.query().eq("parent_id", pid).list();

        return ResponseEntity.ok(CategoryDTO.convertEntityList(list));

    }
}
